﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace wps_demo.Utils
{
    public class WpsUtils
    {
        /// <summary>
        /// 生成Signature
        /// </summary>
        /// <param name="param"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string getSignature(Dictionary<string, string> param, string appSecret)
        {
            string sign = string.Empty;
            List<string> keys = new List<string>();
            foreach (var item in param)
            {
                keys.Add(item.Key);
            }
            // 将所有参数按key的升序排序
            keys.Sort((x, y) => x.CompareTo(y));
            // 构造签名的源字符串
            StringBuilder contents = new StringBuilder();
            foreach (var key in keys)
            {
                if (key == "_w_signature")
                {
                    continue;
                }
                contents.Append(key + "=").Append(param[key]);
            }
            contents.Append("_w_secretkey=").Append(appSecret);
            sign = HMACSHA1(appSecret, contents.ToString());
            sign = HttpUtility.UrlEncode(sign, Encoding.UTF8);
            return sign;
        }

        /// <summary>
        /// HMACSHA1 算法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string HMACSHA1(string key, string data)
        {
            try
            {
                //进行hmac sha1 签名
                HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
                byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(data));
                //字符串经过Base64编码
                return System.Convert.ToBase64String(byteText);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 参数转换成字典集合
        /// </summary>
        /// <param name="paramStr"></param>
        /// <returns></returns>
        public static Dictionary<string, string> paramToMap(string paramStr)
        {
            string[] reParam = paramStr.Split('&');
            Dictionary<string, string> resMap = new Dictionary<string, string>();
            for (int i = 0; i < reParam.Length; i++)
            {
                string[] param = reParam[i].Split('=');
                if (param.Length >= 2)
                {
                    string key = param[0];
                    string value = param[1];
                    for (int j = 2; j < param.Length; j++)
                    {
                        value += "=" + param[j];
                    }
                    resMap.Add(key, value);
                }
            }
            return resMap;
        }

    }
}